using POC.Common;
using Unity.Collections;
using Unity.Entities;
using Unity.NetCode;

namespace Common
{
    public partial struct InitializeDestroyOnTimerSystem : ISystem
    {
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<NetworkTime>();
        }

        public void OnUpdate(ref SystemState state)
        {
            var entityCommandBuffer = new EntityCommandBuffer(Allocator.Temp);
            var simulationTickRate = NetCodeConfig.Global.ClientServerTickRate.SimulationTickRate;
            var currentTick = SystemAPI.GetSingleton<NetworkTime>().ServerTick;

            foreach (var (destroyOnTimer, entity) in SystemAPI.Query<DestroyOnTimer>().WithNone<DestroyAtTick>().WithEntityAccess())
            {
                //计算需要销毁的帧，并给需要销毁的加上DestroyAtTick指定帧销毁组件
                var lifetimeInTicks = (uint)(destroyOnTimer.Value * simulationTickRate);
                var targetTick = currentTick;
                targetTick.Add(lifetimeInTicks);
                entityCommandBuffer.AddComponent(entity, new DestroyAtTick{ Value = targetTick });
            }
            entityCommandBuffer.Playback(state.EntityManager);
        }
    }
}